
#include <cstdlib>
#include <unistd.h>
#include <cstdio>
#include <dirent.h>
#include <fstream>
#include <sys/types.h>
#include <csignal>
#include <cstring>
#include <netinet/in.h>
#include <sys/statvfs.h>
#include <sys/stat.h>
#include <pwd.h>
#include <thread>
#include <disk.hh>

uint64_t disk_load::get_available_free_space() {
    struct statvfs stat;
    struct passwd *pw = getpwuid(getuid());
   
    if (nullptr != pw && 0 == statvfs(pw->pw_dir, &stat)) {
       // printf("path %s\n", pw->pw_dir);
        uint64_t free_bytes = stat.f_bavail * stat.f_frsize;
        return free_bytes;
    }
    return 0ULL;
}

void disk_load::get_disk_space(uint64_t& total_size,uint64_t& free_bytes) {
    struct statvfs stat;
    struct passwd *pw = getpwuid(getuid());

    total_size = 0;
    free_bytes = 0;
   
    if (nullptr != pw && 0 == statvfs(pw->pw_dir, &stat)) {
        //printf("path %s\n", pw->pw_dir);
        free_bytes = stat.f_bavail * stat.f_frsize;
        total_size = stat.f_blocks* stat.f_bsize;

        //printf("stat.f_frsize is %ld,stat.f_bsize is %ld",stat.f_frsize,stat.f_bsize);
        //return free_bytes;
    }   
}

cJSON* disk_load::to_json()
{
    cJSON* cjson = cJSON_CreateObject();
  
    uint64_t total_size,free_bytes;
    get_disk_space( total_size,free_bytes);
    cJSON_AddNumberToObject(cjson, "total_Bytes", total_size); 
    cJSON_AddNumberToObject(cjson, "free_Bytes", free_bytes); 
    return cjson;
}
const char*  disk_load::get_name()
{
    return "disk";
}
disk_load::~disk_load(){

}